/*
 * @Author: xuetao 3168581151@qq.com
 * @Date: 2025-01-23
 * @LastEditors: xuetao 3168581151@qq.com
 * @LastEditTime: 2025-02-08
 * @Description: 联系人服务
 */
import 'package:chat_client/models/contact.dart';
import 'package:chat_client/services/api_service.dart';
import 'package:chat_client/models/user.dart';

import 'package:chat_client/models/apply.dart';
import 'package:chat_client/repositories/contact_repository.dart';

class ContactService {
  // 单例模式
  ContactService._internal();
  static final ContactService _instance = ContactService._internal();
  static ContactService get instance => _instance;

  final ApiService apiService = ApiService.instance;
  final ContactRepository contactRepository = ContactRepository.instance;

  ContactService();

  /// 搜索用户
  Future searchUser(String text) async {
    // 判断是否是纯数字，纯数字则为电话号码
    bool isPhoneNumber = RegExp(r'^\d+$').hasMatch(text);

    // 根据是否是电话号码来判断查询条件
    final params = <String, dynamic>{};
    if (isPhoneNumber) {
      params['phoneNumber'] = text; // 如果是电话号码
    } else {
      params['username'] = text; // 如果是用户名
    }
    // 调用API
    final response = await apiService.get('/contact/search', params: params);
    return response['data'];
  }

  /// 发送申请
  Future sendFriendRequest({
    required User? contact,
    required String applyInfo,
  }) async {
    if (contact != null) {
      final isExistApply = await contactRepository.getApply(contact.userId);
      // 如果该用户已经向本用户发送了待处理好友申请
      if (isExistApply != null &&
          !isExistApply.isSend &&
          isExistApply.status == ApplyStatus.pending.value) {
        throw Exception('请前往处理该用户的好友申请');
      }

      final response = await apiService.post('/contact/apply/send',
          {'contactId': contact.userId, 'applyInfo': applyInfo});

      // 储存申请到本地
      await contactRepository.storeApply(Apply(
          isSend: true,
          opponentId: contact.userId,
          opponentNikename: contact.nickname,
          opponentAvatarUrl: contact.avatarUrl,
          applyInfo: applyInfo,
          status: ApplyStatus.pending.value,
          createdAt: DateTime.now()));
      return response['message'];
    }
  }

  /// 获取远程好友请求列表, 并储存到本地
  Future getRemoteFriendRequestList() async {
    final response = await apiService.get('/contact/apply/list');
    final applicationList = Apply.fromJsonList(response['data']['applyList']);
    await contactRepository.storeApplyList(applicationList);
  }

  // 获取本地好友请求列表
  Future getLocalFriendRequestList() async {
    final applicationList = contactRepository.getAllApplyList();
    return applicationList;
  }

  /// 处理好友请求
  Future handleFriendRequest(String senderId, bool isAccepted) async {
    final response = await apiService.post('/contact/apply/handle',
        {'senderId': senderId, 'isAccepted': isAccepted});
    // 修改本地请求的状态
    if (isAccepted) {
      contactRepository.updateApply(senderId, ApplyStatus.accepted.value);
    }
    if (response['data']['contact'] != null && isAccepted) {
      print(response['data']['contact']);
      await contactRepository
          .setContact(Contact.fromJson(response['data']['contact']));
    }
  }

  // 获取本地联系人列表
  Future getLocalContactList() async {
    final contactList = contactRepository.getContactList();
    return contactList;
  }

  // 获取远程联系人列表, 并储存到本地
  Future getRemoteContactList() async {
    final response = await apiService.get('/contact/list');
    final contactList = Contact.fromJsonList(response['data']['contactList']);
    print(contactList);
    await contactRepository.setContactgetContactList(contactList);
  }

  // 备注好友
  Future remark({required String contactId, required String remark}) async {
    final response = await apiService
        .put('/contact/remark', {'contactId': contactId, 'remark': remark});
    print(response);
    return response;
  }

  // 删除好友
  Future deleteFriend(String contactId) async {
    final response = await apiService
        .delete('/contact/delete', data: {'contactId': contactId});
    print(response);
    return response;
  }

  // 获取好友信息
  Future getFriendInfo(String userId) async {}

  // 更新好友信息
  Future updateFriendInfo(String userId, Map<String, dynamic> userInfo) async {}
}
